package mvc.controllers;

import mvc.framework.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Controller del layout delle pagine
 * 
 * @author Grillo
 */
public class LayoutController extends HttpServlet {
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
   }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            DialogHandler dialogHandler = new DialogHandler(request, response, this.getServletContext());
            
            // Costruzione dell'handler specifico per la richiesta
            IRequestHandler requestHandler = RequestHandlerFactory.getRequestHandler(dialogHandler);

            SessionManager.setRequestHandler(dialogHandler.getSession(), requestHandler);
                    
            // Dispatching della richiesta
            ServletContext servletContext = this.getServletContext();
            RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/layout");
            requestDispatcher.forward(request, response);

        } catch (Exception exc) {
            request.getSession().setAttribute("exception", exc);
            response.sendRedirect("errors/runtimeError.jsp"); // Segnalazione errore!
            exc.printStackTrace();
        } finally { 
            out.close();
        }
    } 
}